import json

from django.db import models


class ChessGrp(models.Model):
    grp_id = models.AutoField(primary_key=True)
    grp_members = models.IntegerField(default=0)

    def to_dict(self):
        _dict = dict()
        _dict['grp_id'] = self.grp_id
        _dict['grp_members'] = self.grp_members
        return _dict

    def __repr__(self):
        return json.dumps(self.to_dict())

    __str__ = __repr__


class ChessUser(models.Model):
    # chess side
    WHITE = 0
    BLACK = 1
    Sides = (
        (WHITE, 'white side'),
        (BLACK, 'block side'),
    )

    # chess role
    PARTICIPANT = 0
    OBSERVER = 1
    Roles = (
        (PARTICIPANT, 'role of participant'),
        (OBSERVER, 'role of observer'),
    )

    # chess client status
    OFFLINE = 1
    ONLINE = 2
    READY = 4
    PAUSE = 8
    Status = (
        (OFFLINE, 'offline status'),
        (ONLINE, 'online status'),
        (READY, 'ready status'),
        (PAUSE, 'pause status'),
    )

    user_id = models.AutoField(primary_key=True)
    session_id = models.CharField(max_length=36, unique=True)
    grp = models.ForeignKey(ChessGrp, on_delete=models.CASCADE)
    role = models.SmallIntegerField(choices=Roles, default=PARTICIPANT)
    side = models.SmallIntegerField(choices=Sides, default=WHITE)
    status = models.IntegerField(choices=Status, default=OFFLINE)

    def to_dict(self):
        _dict = dict()
        _dict['user_id'] = self.user_id
        _dict['session_id'] = self.session_id
        _dict['grp'] = self.grp.grp_id
        _dict['role'] = self.role
        _dict['side'] = self.side
        _dict['status'] = self.status
        return _dict

    def __repr__(self):
        return json.dumps(self.to_dict())

    __str__ = __repr__


class ChessStep(models.Model):
    step_id = models.AutoField(primary_key=True)
    grp = models.ForeignKey(ChessGrp, on_delete=models.CASCADE)
    chess_user = models.ForeignKey(ChessUser, on_delete=models.CASCADE)
    step = models.IntegerField(default=0)
    pos_x = models.IntegerField(default=0)
    pos_y = models.IntegerField(default=0)

    def to_dict(self):
        _dict = dict()
        _dict['step_id'] = self.step_id
        _dict['grp'] = self.grp.grp_id
        _dict['chess_user'] = self.chess_user.user_id
        _dict['step'] = self.step
        _dict['pos_x'] = self.pos_x
        _dict['pos_y'] = self.pos_y
        return _dict

    def __repr__(self):
        return json.dumps(self.to_dict())

    __str__ = __repr__
